package org.com.yz.dubbo.web.ctrl;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.com.yz.common.annotion.Parameter;
import org.com.yz.common.constant.PayConstant;
import org.com.yz.common.util.ClassRefUtil;
import org.com.yz.common.util.MyLog;
import org.com.yz.common.util.ToolUtil;
import org.com.yz.dal.dao.model.AuthenticationDetail;
import org.com.yz.dal.dao.model.BankCard;
import org.com.yz.dal.dao.model.MchsubBindBankCard;
import org.com.yz.dubbo.api.service.IBankCardService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 绑卡接口控制类
 * （含对私、对公；对私采用四要素鉴权，对公采用小额打款鉴权）
 */
@RestController
public class MchsubBindBanKcardCtr {


    @Reference(version = "1.0.0", timeout = 30000, retries = 0)
    public IBankCardService bankCardService;


    private final MyLog _log = MyLog.getLog(MchsubBindBanKcardCtr.class);


    /**
     * 子商户绑定银行卡（0-对公、1-对私）
     * @param data
     * @param sign
     * @return
     */
    @RequestMapping(value = "/api/pay/bankcard.htm")
    @Parameter
    public String bankcard(String data, String sign) {
        MchsubBindBankCard cardRes = new MchsubBindBankCard();
        //转换为对象
        MchsubBindBankCard cardReq = JSONObject.parseObject(StringEscapeUtils.unescapeJava(data), MchsubBindBankCard.class);
        BankCard bankCard = new BankCard();
        //如果鉴权信息已存在，则提示订单号重复(根据订单号查询鉴权明细表)，查询是否存在相同的订单信息（因为鉴权收费问题，插入鉴权表的数据为收费的订单）
        AuthenticationDetail authenticationDetail = bankCardService.checkBankCrad(cardReq.getMchNo(), cardReq.getBizContent().getOrderNo());
        if (ToolUtil.isNotEmpty(authenticationDetail)) {
            bankCard.setStatus(authenticationDetail.getStatus());
            bankCard.setMchAccntNo(authenticationDetail.getMchAccntNo());
            bankCard.setCardNo(authenticationDetail.getCardNo());
            bankCard.setRemark(authenticationDetail.getRemark());
            cardRes.setBizContent(bankCard);
            return ClassRefUtil.createRetData(cardReq, cardRes, PayConstant.RETURN_DEPOSIT_ORDER_NO_EXIST, PayConstant.RETURN_DEPOSIT_ORDER_NO_EXISTS);
        }
        //如果不存在鉴权信息，根据卡号，子商户账户号查询该卡是否已存在（包括成功及处理中），如果已存在，直接返回
        BankCard bankCard1 = bankCardService.checkBankCardInfo(cardReq.getBizContent().getCardNo(), cardReq.getBizContent().getMchAccntNo());
        if (ToolUtil.isNotEmpty(bankCard1)) {
            bankCard.setStatus(bankCard1.getStatus());
            bankCard.setMchAccntNo(bankCard1.getMchAccntNo());
            bankCard.setCardNo(bankCard1.getCardNo());
            bankCard.setRemark(bankCard1.getRemark());
            cardRes.setBizContent(bankCard);
            return ClassRefUtil.createRetData(cardReq, cardRes, PayConstant.RETURN_DEPOSIT_CARD_EXIT, PayConstant.RETURN_DEPOSIT_CARD_EXITS);
        }
        //对公对私鉴权
        try {
            //1:对私
            if ("1".equals(cardReq.getBizContent().getCardAccntType())) {
                bankCard = bankCardService.bandCardHandle(cardReq.getBizContent(), cardReq.getMchNo(), cardReq.getOutTransNo(), cardReq.getBizType());
                //0:对公
            } else if ("0".equals(cardReq.getBizContent().getCardAccntType())) {
                bankCard = bankCardService.binkCompanyCard(cardReq.getMchNo(), cardReq.getBizContent());
            }

            //如果绑卡接口请求 失败，直接返回外层fail，业务数据为空
            if ("error".equals(bankCard.getStatus())) {
                cardRes.setBizContent(null);
                return ClassRefUtil.createRetData(cardReq, cardRes, PayConstant.RETURN_DEPOSIT_CARD_ERROR, PayConstant.RETURN_DEPOSIT_CARD_ERRORS + "{" + bankCard.getErrmsg() + "}");
            } else {
                //如果绑卡接口请求成功，统一返回外层的success，业务数据里status表示认证状态 to_verify:待认证 success：认证成功 fail：认证失败 to_handle：认证处理中
                BankCard bankCardRes = new BankCard();
                bankCardRes.setMchAccntNo(bankCard.getMchAccntNo());
                bankCardRes.setStatus(bankCard.getStatus());
                bankCardRes.setRemark(bankCard.getRemark());
                bankCardRes.setCardNo(bankCard.getCardNo());
                cardRes.setBizContent(bankCardRes);
                return ClassRefUtil.createRetData(cardReq, cardRes, PayConstant.RETURN_DEPOSIT_SUCESS, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
            }
        } catch (Exception e) {
            cardRes.setBizContent(null);
            return ClassRefUtil.createRetData(cardReq, cardRes, PayConstant.RETURN_DEPOSIT_CODE_ERROR, PayConstant.RETURN_DEPOSIT_CODES_ERROR);
        }
    }


    /**
     * @param data, sign]
     * @Description: 解绑银行卡
     * @author wzc
     * @date 2018/7/20 10:58
     */
    @RequestMapping(value = "/api/pay/bankcardUntie.htm")
    @Parameter
    public String bankcardUntie(String data, String sign) {
        //转换为json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(StringEscapeUtils.unescapeJava(data));
        //转换为对象
        MchsubBindBankCard card = JSONObject.toJavaObject(jsonObject, MchsubBindBankCard.class);
        MchsubBindBankCard res = new MchsubBindBankCard();
        try {
            BankCard bankCard = new BankCard();
            bankCard.setMchAccntNo(card.getBizContent().getMchAccntNo());
            bankCard.setCardNo(card.getBizContent().getCardNo());
            List<BankCard> bankCardList = bankCardService.selectBankCard(bankCard);
            if (bankCardList.size() > 0) {
                //已解绑状态
                if ("untie".equals(bankCardList.get(0).getStatus())) {
                    res.setBizContent(null);
                    return ClassRefUtil.createRetData(card, res, PayConstant.RETURN_DEPOSIT_CARD_UNUSE, PayConstant.RETURN_DEPOSIT_CARDNO_UNUSE);
                }
            } else {
                //卡号不存在
                res.setBizContent(null);
                return ClassRefUtil.createRetData(card, res, PayConstant.RETURN_DEPOSIT_CARD_NULL, PayConstant.RETURN_DEPOSIT_CARD_NULLS);
            }
            //执行解绑逻辑
            int result = bankCardService.bandCardUntieHandle(card);
            if (result < 0) {
                _log.info("解绑失败");
            }
            return ClassRefUtil.createRetData(card, card, PayConstant.RETURN_DEPOSIT_SUCESS, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
        } catch (Exception e) {
            _log.error(e, "数据格式有误！");
            res.setBizContent(null);
            return ClassRefUtil.createRetData(card, res, PayConstant.RETURN_DEPOSIT_CODE_ERROR, PayConstant.RETURN_DEPOSIT_CODES_ERROR);
        }
    }


}


